#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define LIFES 3
#define USERNAME_SIZE 20

char username[USERNAME_SIZE];

typedef struct User{
  char username[USERNAME_SIZE];
  int victories;
} User;

User *users = NULL;
int userCount = 0;

void showNumbers();
void showMenu();
int playGame();
void addUserVictory(const char *username);
void showScoreboard();
void freeMemory();

int main (){
  srand(time(NULL));
  int optionForMenu;
  
  do {
    showMenu();
    scanf("%d", &optionForMenu);
    
    switch (optionForMenu){
      case 1:
        if (playGame()){
          printf("Congratulations, %s! You Win!!!\n\n", username);
          addUserVictory(username);
          showScoreboard();
          printf("\n");
        } else{
          printf("Sorry, %s, You Lose! :(\n\n", username);
        }
        break;
    
      case 2:
        showScoreboard();
        break;
    }
    
  } while(optionForMenu != 3);
  
  freeMemory();
  
  return 0;
}

void showNumbers(){
  int numbers[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      printf(" | %d | ", numbers[i][j]);
    }
    printf ("\n");
  }
}

void showMenu(){
  printf("====Lottery🎲====\n");
  printf("= 1-) Play!\n");
  printf("= 2-) Scoreboard\n");
  printf("= 3-) Exit\n");
  printf("=================\n");
  printf("*->Chose a option: ");
}

int playGame(){
  int winNumber = (rand() % 9) + 1;
  int option;
  int count = 0;
  
  printf("Enter your username (Please don't use spaces): ");
  scanf("%19s", username);
  
  while(count < LIFES){
    showNumbers();
    printf("\nPick a number: ");
    scanf("%d", &option);
    
    if (option < 1 || option > 9){
      printf("Invalid choice. Please choose a number between 1 and 9.\n");
    } else if (option == winNumber){
      return 1; //indica que o jogador ganhou
    } else{
      printf("Try again...\n");
    }
    
    count++;
  }
  
  return 0; //indica que o jogador perdeu
}

void addUserVictory(const char *username){
  for (int i = 0; i < userCount; i++){
    if(strcmp(users[i].username, username) == 0){
      users[i].victories++;
      return;
    }
  }
  
  users = (User *)realloc(users, (userCount +1) * sizeof(User));
  
  strcpy(users[userCount].username, username);
  users[userCount].victories = 1;
  userCount++;
}

void showScoreboard(){
  printf("==== Scoreboard ====\n");
  for (int i = 0; i < userCount; i++){
    printf("%s: %d Victories\n", users[i].username, users[i].victories);
  }
  printf("====================\n");
}

void freeMemory(){
  free(users);
}
